<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>DeepSeek 聊天助手</title>
    <script src="/static/js/vue.global.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <link rel="stylesheet" href="/static/css/font-awesome.min.css">
    <link rel="stylesheet" href="/static/css/base.css">
</head>

<body>
    <div id="app" class="app-container">
        <div class="message-content">[[ outputText ]]</div>

        <div class="chat-input-container">
            <textarea class="chat-input" v-model="newMessage" placeholder="输入消息..."></textarea>
            <button class="send-btn" @click="sendMessage()">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>
    <script>
        const { createApp, reactive, toRefs } = Vue;
        const app = createApp({
            setup() {
                const state = reactive({
                    newMessage: '',    // 输入框内容
                    outputText: '',    // AI 输出内容
                    isLoading: false   // 加载状态
                });

                // 核心发送消息函数（带流式实时显示）
                const sendMessage = async () => {
                    const input = state.newMessage.trim();
                    if (!input) return;

                    // 重置状态
                    state.isLoading = true;
                    state.outputText = '';
                    state.newMessage = '';

                    try {
                        // 1. 发送请求（支持自定义 headers）
                        const response = await fetch(`{{ url_for('chat.stream_chat') }}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ message: input })
                        });

                        if (!response.ok) throw new Error(`请求失败: ${response.status}`);

                        // 2. 处理流式响应
                        const reader = response.body.getReader();
                        const decoder = new TextDecoder();

                        // 循环读取流数据
                        while (true) {
                            const { done, value } = await reader.read();
                            if (done) break;

                            // 3. 实时解码并更新输出（打字机效果）
                            const chunk = decoder.decode(value, { stream: true });
                            const data = JSON.parse(chunk);

                            // 逐字追加（控制速度模拟打字效果）
                            for (const char of data.content) {
                                state.outputText += char;
                                await new Promise(resolve => setTimeout(resolve, 10)); // 打字速度
                            }
                        }

                    } catch (err) {
                        state.outputText = `错误: ${err.message}`;
                    } finally {
                        state.isLoading = false;
                    }
                };

                return { ...toRefs(state), sendMessage };
            }
        });
        // Vue3 分隔符配置
        app.config.compilerOptions.delimiters = ['[[', ']]'];
        app.mount('#app');
    </script>
</body>

</html>